const storageSignKey = "juejin-daily-check-in/last_sign_timestamp";
const storageLotteryKey = "juejin-daily-check-in/last_lottery_timestamp";

// 获取上一次签到的日子
const lastSignNumberOfDays = GM_getValue(storageSignKey, 0);
const lastLotteryNumberOfDays = GM_getValue(storageLotteryKey, 0);
// 计算现在所在的日子
const currentDate = new Date();
const currentNumberOfDays = Math.floor(
  (currentDate.valueOf() - currentDate.getTimezoneOffset() * 60 * 1000) /
    1000 /
    60 /
    60 /
    24
);

class CheckInError extends Error {}

function fetch(
  url: string,
  method: "POST" | "GET" | "HEAD" = "GET"
): Promise<{
  [key: string]: any;
}> {
  return new Promise((resolve, reject) => {
    GM_xmlhttpRequest({
      url,
      method,
      headers: {
        "content-type": "application/json",
        "user-agent": navigator.userAgent,
        origin: "",
      },
      responseType: "json",
      onload(response) {
        try {
          if (response.status === 200) {
            const data = response.response;
            if (data.err_msg === "success") {
              resolve(data.data);
            } else {
              reject(new CheckInError(data.err_msg));
            }
          }
        } catch (e) {
          reject(e);
        }
      },
    });
  });
}

(async function start() {
  // 如果今天已经请求过，不再请求
  try {
    if (currentNumberOfDays !== lastSignNumberOfDays) {
      await fetch("https://api.juejin.cn/growth_api/v1/check_in", "POST");

      // 更新最近一次签到的日子
      GM_setValue(storageSignKey, currentNumberOfDays);
    }
  } catch (e) {
    if (e instanceof CheckInError) {
      GM_setValue(storageSignKey, currentNumberOfDays);
    }
    console.error("juejin-check-in", e);
  }

  try {
    if (currentNumberOfDays !== lastLotteryNumberOfDays) {
      const todayLotteryStatus = await fetch(
        "https://api.juejin.cn/growth_api/v1/lottery_config/get"
      );

      if (todayLotteryStatus.free_count > 0) {
        await fetch("https://api.juejin.cn/growth_api/v1/lottery/draw", "POST");

        GM_setValue(storageLotteryKey, currentNumberOfDays);
      } else {
        GM_setValue(storageLotteryKey, currentNumberOfDays);
      }
    }
  } catch (e) {
    console.error("juejin-lottery", e);
  }
})();
